package me.jiatao.wan.ui.main.project

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.paging.LoadState
import com.hi.dhl.binding.viewbind
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.distinctUntilChangedBy
import me.jiatao.wan.R
import me.jiatao.wan.common.ui.LazyFragment
import me.jiatao.wan.common.ui.LoadingLottieAnimation
import me.jiatao.wan.databinding.FragmentRecyclerViewBinding
import me.jiatao.wan.paging3.footer.FooterAdapter
import me.jiatao.wan.paging3.home.HomeArticleAdapter
import timber.log.Timber

/**
 * @Author: taojia
 * @CreateDate: 2021/8/31 6:44 下午
 * @Version: 1.0
 * @Description:
 */

@AndroidEntryPoint
class ArticleListFragment : LazyFragment() {

    private val projectViewModel: ProjectViewModel by viewModels()
    private val mBinding: FragmentRecyclerViewBinding by viewbind()
    private val articlePagingAdapter by lazy { HomeArticleAdapter() }

    /**
     * 参数传递
     */
    companion object {
        private const val COURSE_ID = "COURSE_ID"

        fun newInstance(arg: Int) =
            ArticleListFragment().apply {
                arguments = Bundle().apply {
                    putInt(COURSE_ID, arg)
                }
            }
    }

    private var courseId: Int = -1
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        courseId = arguments?.getInt(COURSE_ID) ?: -1
    }


    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_recycler_view, container, false)
    }

    override fun initView(view: View) {
        super.initView(view)

        Timber.e("ArticleListFragment onViewCreated--> $courseId")

        /** 根据加载状态显示刷新状态 */
        lifecycleScope.launchWhenCreated {
            Timber.e("ArticleListFragment launchWhenResumed--> $courseId")
            articlePagingAdapter.loadStateFlow
                .distinctUntilChangedBy { it.refresh }
                .collectLatest { states ->
                    mBinding.swiperRefresh.isRefreshing = states.refresh is LoadState.Loading

                    Timber.e("articlePagingAdapter.itemCount ${articlePagingAdapter.itemCount}")

                    when (states.refresh) {
                        is LoadState.NotLoading -> {
                            println("refresh ---> NotLoading")
                            projectViewModel.loadingState.value = LoadingLottieAnimation.State.COMPLETE
                        }
                        is LoadState.Loading -> {
                            println("refresh ---> Loading")
                            if (articlePagingAdapter.itemCount == 0) {
                                projectViewModel.loadingState.value = LoadingLottieAnimation.State.LOADING
                            }
                        }
                        is LoadState.Error -> {
                            println("refresh ---> Error: " + Thread.currentThread().name)
                            if (articlePagingAdapter.itemCount == 0) {
                                projectViewModel.loadingState.value = LoadingLottieAnimation.State.ERROR
                            }
                            Toast.makeText(
                                requireContext(),
                                (states.refresh as LoadState.Error).error.message,
                                Toast.LENGTH_SHORT
                            ).show()
                        }
                    }
                }
        }
    }


    override fun initData() {
        super.initData()

        if (courseId == -1) {
            Toast.makeText(requireContext(), "列表ID为空", Toast.LENGTH_SHORT).show()
            return
        }

        mBinding.apply {
            recyclerView.adapter =
                articlePagingAdapter.withLoadStateFooter(FooterAdapter(articlePagingAdapter))

            swiperRefresh.setOnRefreshListener {
                articlePagingAdapter.refresh()
            }
        }
        /**
         * 加载文章列表
         */
        projectViewModel.loadProjectArticleListVM(courseId).observe(viewLifecycleOwner) {
            articlePagingAdapter.submitData(lifecycle, it)
            mBinding.swiperRefresh.isRefreshing = false
        }
    }
}